package com.example.scaletest.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.example.scaletest.R;
import com.example.scaletest.batch.BatchService;
import com.example.scaletest.bean.BatchData;
import com.example.scaletest.bean.BindData;
import com.example.scaletest.bean.ProductData;
import com.example.scaletest.db.DataDao;
import com.example.scaletest.scanner.CaptureActivity;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.os.Handler;

public class CarActivity extends Activity implements View.OnClickListener{
    private ImageView image_deviceScan;
    private ImageView image_goodsScan;
    private EditText device;
    private EditText goods;
    private ImageView picture;
    private Button takePhoto;
    private Uri imageUri;
  private  File outputImage;
    private LinearLayout bind;

    private ArrayList<File>files;
    private Map<String, String> params;
    Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case UploadService.UPLOAD_SUCCESS:
                    Toast.makeText(CarActivity.this, "success", Toast.LENGTH_LONG).show();
                    break;
                case UploadService.UPLOAD_FAIL:
                    Toast.makeText(CarActivity.this, "fail", Toast.LENGTH_LONG).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.carbind);

        image_deviceScan = (ImageView) findViewById(R.id.deviceScan);
        image_deviceScan.setOnClickListener(CarActivity.this);
        image_goodsScan = (ImageView) findViewById(R.id.goodsScan);
        image_goodsScan.setOnClickListener(CarActivity.this);

        takePhoto=(Button) findViewById(R.id.takePhoto);
        takePhoto.setOnClickListener(CarActivity.this);
        picture=(ImageView) findViewById(R.id.picture);

        bind = (LinearLayout) findViewById(R.id.bind);
        bind.setOnClickListener(CarActivity.this);


        device = (EditText) findViewById(R.id.device);
        goods = (EditText) findViewById(R.id.goods);
        files=new ArrayList<File>();
        params=new HashMap<String, String>();
    }

    public void onClick(View v){
        switch (v.getId()){
            case R.id.deviceScan:
                Intent intent = new Intent(CarActivity.this, CaptureActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.goodsScan:
                intent = new Intent(CarActivity.this, CaptureActivity.class);
                startActivityForResult(intent,2);
                break;
            case R.id.takePhoto:
              outputImage = new File(Environment.getExternalStorageDirectory(),"output_image.jpg");
                try{
                    if(outputImage.exists()){
                        outputImage.delete();
                    }
                    outputImage.createNewFile();

                } catch(IOException e){
                    e.printStackTrace();
                }
                imageUri =Uri.fromFile(outputImage);
                Intent intent2 = new Intent("android.media.action.IMAGE_CAPTURE");
                intent2.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                startActivityForResult(intent2, 3);
                break;
            case R.id.bind:
                files.clear();
                params.clear();
                int i=0;
                files.add(outputImage);
                StringBuffer sbFileTypes=new StringBuffer();
                for (File tempFile:files) {
                    String fileName=tempFile.getName();
                    sbFileTypes.append(getFileType(fileName));
                }
                params.put("fileTypes",sbFileTypes.toString());
                params.put("method", "upload");
                String device_id = device.getText().toString();
                String goods_id = goods.getText().toString();
                params.put("sensor",device_id);
                params.put("carNumber",goods_id);
                UploadService uploadService=new UploadService(mHandler);
                uploadService.uploadFileToServer(params, files);



        /*    case R.id.download:
                intent = new Intent(CarActivity.this,BatchService.class);
                String firm= LoginActivity.firm_id;
                intent.putExtra("request","{\"firm_id\":\""+ firm + "\"}");
                // intent.putExtra("request","{\"firm_id\":\"1\"}");
              //  product.setVisibility(View.INVISIBLE);
               // batch.setVisibility(View.INVISIBLE);
               // batchId = "";
                Toast.makeText(this,"������",Toast.LENGTH_SHORT).show();
                startService(intent);
                break;*/
          /*  case R.id.bind:
                String device_id = device.getText().toString();
                String goods_id = goods.getText().toString();
              //  if (batchId.isEmpty()){
                    Toast.makeText(CarActivity.this,"�������ز�Ʒ��ѡ������",Toast.LENGTH_SHORT).show();
              //  }else{
                    if(device_id.isEmpty() || goods_id.isEmpty()) {
                        Toast.makeText(CarActivity.this,"��ɨ���豸ID����ƷID",Toast.LENGTH_SHORT).show();
                    }else{
                        BindData bindData = new BindData();
                        dataDao.deleteBindData();
                   //     bindData.setBatchId(batchId);
                        bindData.setDeviceId(device_id);
                        bindData.setGoodsId(goods_id);
                        dataDao.addBindData(bindData);
                        intent = new Intent(CarActivity.this, NetWorkService.class);
                        // intent.putExtra("request","{\"firm_id\":\"1\"}");
                        String firm2= LoginActivity.firm_id;
                        intent.putExtra("request","{\"firm_id\":\""+ firm2 + "\"}");
                        startService(intent);
                    }

                break;
                */
            default:

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        switch (requestCode){
            case 1:
                if (resultCode == RESULT_OK){
                    device.setText(data.getStringExtra("result"));
                }
                break;
            case 2:
                if(resultCode == RESULT_OK){
                    goods.setText(data.getStringExtra("result"));
                }
                break;
            case 3:
                if (resultCode == RESULT_OK) {
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    intent.setDataAndType(imageUri, "image/*");
                    intent.putExtra("scale", true);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, 4);
                }
                break;
            case 4:
                if (resultCode == RESULT_OK) {
                    try{
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);

                    } catch(FileNotFoundException e){
                        e.printStackTrace();
                    }
                }
                break;
            default:
        }
    }

    private String getFileType(String fileName) {
        // TODO Auto-generated method stub
        return fileName.substring(fileName.lastIndexOf("."), fileName.length());
    }
    protected void onDestroy(){
        super.onDestroy();
      //  unregisterReceiver(broadcastReceiver);
    }
}
